package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.itheima.dto.PageComDto;
import com.itheima.commen.ReturnSuccess;
import com.itheima.pojo.Articles;
import com.itheima.service.ArticlesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/articles")
public class ArticlesController {
    @Autowired
    private ArticlesService articlesService;
    @GetMapping()
    public PageComDto search(Integer page,Integer pagesize,String keyword,Integer state ){
        //查询文章
        PageComDto pageComDto=articlesService.search(page,pagesize,keyword,state);
        return pageComDto;
    }
    @PostMapping()
    public Map<String,Integer> idMap(@RequestBody Articles articles){
        //添加文章,返回id

        articles.setState(1);
        //暂无user
        articles.setCreatorID(2);
        articles.setCreateTime(new Date());
        boolean save = articlesService.save(articles);
        Map<String, Integer> map = new HashMap<>();
        map.put("id",articles.getId());
        if(save){
            return map;
        }
        return null;
    }
     @DeleteMapping("/{id}")
    public ReturnSuccess delete(@PathVariable Integer id){
        //删除文章

         boolean b = articlesService.removeById(id);
         if(b){
             return ReturnSuccess.success();
         }
             return ReturnSuccess.error();
     }
     @PostMapping("/{id}/{state}")
     //修改文章状态
    public ReturnSuccess state(@PathVariable Integer id,@PathVariable Integer state){
        LambdaUpdateWrapper<Articles> wrapper=new LambdaUpdateWrapper<>();
         wrapper.set(Articles::getState,state).eq(Articles::getId,id);
         boolean update = articlesService.update(wrapper);
         if(update){
             return ReturnSuccess.success();
         }
         return ReturnSuccess.error();
     }
     @PutMapping("{id}")
     //编辑文章
    public ReturnSuccess update(@RequestBody Articles articles,@PathVariable Integer id){
         LambdaUpdateWrapper<Articles> wrapper=new LambdaUpdateWrapper<>();
         wrapper.eq(Articles::getId,id);
         boolean update = articlesService.update(articles, wrapper);
         if(update){
             return ReturnSuccess.success();
         }
         return ReturnSuccess.error();
     }
     @GetMapping("/{id}")
     //展示文章
    public Articles getById(@PathVariable Integer id){
         Articles articles = articlesService.getById(id);
         return articles;
     }
}

